<?php
/**
 * svn cat -r revision svn://ip/path/file --username user --password pass
 * @author Alan.H
 */
require_once dirname(__FILE__) . "/../Command.php";

class Cat extends Command {
    /**
     * 版本号
     * @var null
     */
    protected $revision = null;

    /**
     * 文件路径
     * @var null
     */
    protected $path = null;

    /**
     * @param $revision
     * @return $this
     */
    public function setRevision($revision) {
        $this->revision = $revision;
        return $this;
    }

    /**
     * @param $path
     * @return $this
     */
    public function setPath($path) {
        $this->path = $path;
        return $this;
    }

    /**
     * @return $this|mixed
     * @throws Exception
     */
    public function execCmd() {
        if ( ! $this->revision) {
            throw new InvalidArgumentException('Revision is empty!');
        }

        if ( ! $this->path) {
            throw new InvalidArgumentException('Path is empty!');
        }

        $cmd = [
            'svn',
            'cat',
            '-r',
            $this->revision,
            rtrim($this->log->getRoot(), '/') . '/' . ltrim($this->path),
            '--username',
            $this->log->getUsername(),
            '--password',
            $this->log->getPassword(),
        ];

        $name = md5(rtrim($this->log->getRoot(), '/') . '/' . ltrim($this->path)) . '.' .  $this->revision;
        $file = $this->log->getRuntime() . '/' . $name . '.' . pathinfo($this->path, PATHINFO_EXTENSION);
        $cmd[] = '>';
        $cmd[]= $file;

        if ( ! file_exists($file)) {
            exec(join(' ', $cmd));
        }

        $this->file = $file;
        return $this;
    }
}